在每張專輯頁面新增「隨機播放一首」按鈕,使用戶可以隨機點擊播放專輯內的任意一首歌曲。
目前專輯頁面已經能夠顯示專輯資訊、專輯封面、以及歌曲列表。
今天的目標是:
在專輯資訊 <div>
中新增按鈕:
<button id="random-play-btn" class="purple-btn">隨機播放一首</button>
為按鈕設計紫色漸層、圓角及懸停效果:
.purple-btn {
background: linear-gradient(135deg, #6b568a, #6d4cb5); /* 漸層紫色 */
border: none;
border-radius: 12px;
color: white;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s ease;
margin: 10px 0;
}
.purple-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(128, 90, 213, 0.4);
}
在 album.js 中加入隨機播放邏輯:
// 隨機播放按鈕
const randomBtn = document.getElementById("random-play-btn");
randomBtn.addEventListener("click", () => {
// 隨機選一首
const randomSong = album.songs[Math.floor(Math.random() * album.songs.length)];
const url = typeof randomSong === "string" ? "#" : randomSong.url;
if (url !== "#") {
window.open(url, "_blank"); // 在新分頁打開
} else {
alert("這首歌沒有連結可以播放!");
}
});
const randomBtn = document.getElementById("random-play-btn");
randomBtn.addEventListener("click", () => {
const randomSong = album.songs[Math.floor(Math.random() * album.songs.length)];
album.songs
是當前專輯的歌曲陣列。Math.random()
會產生 0 ~ 1 之間的隨機數字。Math.random() * album.songs.length
就會變成 0 到 歌曲數量 之間的數。Math.floor(...)
會把這個數字取整數,變成陣列索引。const url = typeof randomSong === "string" ? "#" : randomSong.url;
if (url !== "#") {
window.open(url, "_blank");
} else {
alert("這首歌沒有連結可以播放!");
}